﻿$(function () {
    var r = new RegExp("\\(([^\)]+?)\\)", "ig");

    var setSecurity = function (sender, attrName) {

        var attr = $(sender).attr(attrName);

        if (!attr) return;

        var result, arr;

        while ((result = r.exec(attr)) != null) {

            arr = result[1].split('.');

            if (arr.length != 2) continue;

            var actionOpt = arr[0], activityOpt = arr[1];

            switch (attrName) {
                case "_enable_":
                    if ((actionOpt === "*" || actionType === actionOpt)
                    && (activityOpt === "*" || activityName === activityOpt)) {
                        $(sender).attr("disabled", false).removeAttr("disabled");
                    }
                    break;

                case "_disable_":
                    if ((actionOpt === "*" || actionType === actionOpt)
                    && (activityOpt === "*" || activityName === activityOpt)) {
                        $(sender).attr((sender.attr("tagName") == 'select' ? "disabled" : "readonly"), true)
                            .attr("validator", "").removeAttr("validator")
                            .find("[validator]").attr("validator", "").removeAttr("validator");
                        $(sender).find("input,textarea").attr("readonly", true).css("color", "#CCC").css("border", "0px");
                        $(sender).find("select").attr("disabled", true).css("color", "#CCC");
                    }
                    break;

                case "_visible_":
                    if ((actionOpt === "*" || actionType === actionOpt)
                    && (activityOpt === "*" || activityName === activityOpt)) {
                        $(sender).show();
                    }
                    break;

                case "_hidden_":
                    if ((actionOpt === "*" || actionType === actionOpt)
                    && (activityOpt === "*" || activityName === activityOpt)) {
                        $(sender).hide().attr("validator", "").removeAttr("validator")
                            .find("[validator]").attr("validator", "").removeAttr("validator")
                    }
                    break;
            }
        }
    };

    $("[_enable_],[_disable_],[_visible_],[_hidden_]").each(function () {
        var sender = $(this);

        if (sender.attr("_disable_")) {
            setSecurity(sender, "_disable_");
        }

        if (sender.attr("_enable_")) {
            setSecurity(sender, "_enable_");
        }

        if (sender.attr("_hidden_")) {
            setSecurity(sender, "_hidden_");
        }

        if (sender.attr("_visible_")) {
            setSecurity(sender, "_visible_");
        }
    });
});